package org.classg.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.classg.edu.entity.Subject;
import org.classg.edu.vo.excel.SubjectData;
import org.classg.edu.service.SubjectService;
import org.classg.servicebase.exception.MyException;

import java.util.Map;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private SubjectService subjectService;
    public SubjectExcelListener() {}
    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    // 一行一行去读excel内容
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        // 判断是否没有文件
        if (subjectData == null) {
            throw new MyException(20001, "添加失败，文件为空");
        }
        // 添加一级分类
        Subject oneSubject = queryExcelOneSubject(subjectService, subjectData.getOneSubjectDataName());
        // 判断数据库中是否有相同的
        if (oneSubject == null) {
            // 没有相同的
            oneSubject = new Subject();
            oneSubject.setTitle(subjectData.getOneSubjectDataName());
            oneSubject.setParentId("0");
            subjectService.save(oneSubject);
        }

        // 获取一级分类的id值
        String parentId = oneSubject.getId();

        // 添加二级分类
        Subject twoSubject = queryExcelTwoSubject(subjectService, subjectData.getTwoSubjectDataName(), parentId);
        // 判断数据库中是否有相同的
        if (twoSubject == null) {
            // 没有相同的
            twoSubject = new Subject();
            twoSubject.setTitle(subjectData.getTwoSubjectDataName());
            twoSubject.setParentId(parentId);
            subjectService.save(twoSubject);
        }
    }



    // 读取完成后执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    // 读取excel表头信息
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("表头信息："+headMap);
    }

    // 查询一级分类是否重复
    private Subject queryExcelOneSubject(SubjectService subjectService, String name) {
        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<Subject>().eq(Subject::getTitle, name).eq(Subject::getParentId, 0);
        Subject subject = subjectService.getOne(wrapper);
        return subject;
    }

    // 查询二级分类是否重复
    private Subject queryExcelTwoSubject(SubjectService subjectService, String name, String parentId) {
        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<Subject>().eq(Subject::getTitle, name).eq(Subject::getParentId, parentId);
        Subject subject = subjectService.getOne(wrapper);
        return subject;
    }
}
